# encoding: utf-8
# @author: w4dll
# @file: usermanage_pane.py
# @time: 2020/5/6 22:01

from PyQt5.Qt import*
from resource.tk_guanli import Ui_Form
from mytool import sqlite3Class

class tkGuanli(QWidget, Ui_Form):
    # tk_guanli_complete = pyqtSignal()
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.db = sqlite3Class("data.db")
        self.initUi()

    # 初始化界面
    def initUi(self):
        self.tiku = self.db.selectdata("select * from t_timu")
        first_row = ["题号", "适用人员", "专业分类", "题干", "题型", "选项1", "选项2", "选项3", "选项4", "选项5", "选项6", "选项7", "选项8", "选项9",
                     "选项10", "答案", "备注"]
        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(first_row)

        # 添加数据
        for item in self.tiku:
            list_q = []
            for x in item:
                list_q.append(QStandardItem(str(x)))
            self.model.appendRow(list_q)

        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置表格的选取方式是行选取

    # 选中行
    def row_selected(self):
        self.pushButton.setEnabled(True)

    # 删除行
    def delete_row(self):
        for index in self.tableView.selectedIndexes():
            self.model.removeRow(index.row())
        self.pushButton.setEnabled(False)

    # 确定按钮
    def on_ok(self):
        if QMessageBox.No == QMessageBox.question(self, "提示", "是否保存更改？"):
            return

        # todo 优化存储设计
        rowcount = self.model.rowCount()
        colcount = self.model.columnCount()
        ls1 = []
        for i in range(rowcount):
            ls = tuple()
            for j in range(colcount):
                index = self.model.index(i, j)
                s = self.model.data(index)
                ls += (s, )
            ls1.append(ls)
        self.db.excuteSql("delete from t_timu")
        sql = "insert into t_timu(ID, 适用人员, 专业分类, 题干, 题型," \
              "选项1, 选项2, 选项3, 选项4, 选项5, 选项6, 选项7, 选项8,选项9,选项10," \
              "答案,备注) values(?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
        for x in ls1:
            self.db.insert_singlerow_data(sql, x)
        self.close()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win = tkGuanli()
    win.show()
    sys.exit(app.exec_())